package com.mall.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

@Component
@Slf4j
public class CreatePromoOrderConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("create_promo_order_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                MessageExt message = msgs.get(0);
                CreateSeckillOrderResponse promoOrder = null;
                try {
                    byte[] body = message.getBody();
                    String requestStr = new String(body, 0, body.length, Charset.forName("utf-8"));

                    CreateSeckillOrderRequest request = JSON.parseObject(requestStr, CreateSeckillOrderRequest.class);
                    promoOrder = orderPromoService.createPromoOrder(request);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 根据调用结果决定，返回消费成功还是失败
                if (OrderRetCode.SUCCESS.getCode().equals(promoOrder.getCode())) {
                    // 创建订单成功
                    log.info("秒杀业务创建订单成功:{}", promoOrder);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                // 创建订单失败
                log.info("秒杀业务创建订单失败:{}", promoOrder);
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });


        try {
            consumer.subscribe("create_promo_order", "*");

            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
